import React, { useState, useEffect } from 'react';
import {
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Button,
    TextField,
    Box,
    Typography,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    FormHelperText,
    CircularProgress,
    Alert,
    Divider,
    SelectChangeEvent,
    IconButton,
    useTheme,
    useMediaQuery,
    Autocomplete
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import WorkIcon from '@mui/icons-material/Work';
import {
    getOfferTypeOptions,
    getOfferStatusOptions,
    fuzzySearchOfferArea,
    fuzzySearchOfferSchool,
    fuzzySearchOfferProgram,
    getProjectTypeOptions
} from '../../../api';

// 添加工作信息参数接口
interface AddWorkExperienceParams {
    uid?: string;
    sid: string;
    record_id: string;
    offer_type: string;
    company_college_name: string;
    position_project_name: string;
    industry_name: string;
    location: string; // 地点字段
    project_type: string; // 项目类型字段
    salary_month: string;
    salary_year: string;
    accept_status: string;
    remark: string;
}

interface AddWorkExperienceDialogProps {
    open: boolean;
    onClose: () => void;
    onAdd: (params: AddWorkExperienceParams) => Promise<void>;
    sid: string;
    record_id: string;
}

const AddWorkExperienceDialog: React.FC<AddWorkExperienceDialogProps> = ({ open, onClose, onAdd, sid, record_id }) => {
    const theme = useTheme();
    const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
    // 表单数据
    const [formData, setFormData] = useState<AddWorkExperienceParams>({
        sid,
        record_id,
        offer_type: '',
        company_college_name: '',
        position_project_name: '',
        industry_name: '',
        location: '',
        project_type: '',
        salary_month: '',
        salary_year: '',
        accept_status: '',
        remark: ''
    });

    // 表单验证错误
    const [errors, setErrors] = useState<Record<string, string>>({});

    // 加载状态
    const [loading, setLoading] = useState<boolean>(false);

    // 错误信息
    const [error, setError] = useState<string | null>(null);

    // Offer类型选项
    const [offerTypeOptions, setOfferTypeOptions] = useState<string[]>([]);

    // Offer状态选项
    const [offerStatusOptions, setOfferStatusOptions] = useState<string[]>([]);

    // 项目类型选项
    const [projectTypeOptions, setProjectTypeOptions] = useState<string[]>([]);

    // 地区选项
    const [locationOptions, setLocationOptions] = useState<string[]>([]);

    // 地区搜索加载状态
    const [locationSearchLoading, setLocationSearchLoading] = useState<boolean>(false);

    // 地区搜索输入值
    const [locationSearchInput, setLocationSearchInput] = useState<string>('');

    // 学校名称选项
    const [schoolOptions, setSchoolOptions] = useState<string[]>([]);

    // 学校名称搜索加载状态
    const [schoolSearchLoading, setSchoolSearchLoading] = useState<boolean>(false);

    // 学校名称搜索输入值
    const [schoolSearchInput, setSchoolSearchInput] = useState<string>('');

    // 职位/项目选项
    const [programOptions, setProgramOptions] = useState<string[]>([]);

    // 职位/项目搜索加载状态
    const [programSearchLoading, setProgramSearchLoading] = useState<boolean>(false);

    // 职位/项目搜索输入值
    const [programSearchInput, setProgramSearchInput] = useState<string>('');

    // 处理输入变化
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target;
        setFormData((prev) => ({
            ...prev,
            [name]: value
        }));

        // 清除对应字段的错误
        if (errors[name]) {
            setErrors((prev) => ({
                ...prev,
                [name]: ''
            }));
        }
    };

    // 处理选择变化
    const handleSelectChange = (e: SelectChangeEvent) => {
        const name = e.target.name as string;
        const value = e.target.value as string;

        setFormData((prev) => ({
            ...prev,
            [name]: value
        }));

        // 如果是offer_type字段变化，清除不相关字段的值
        if (name === 'offer_type') {
            if (value === '就业') {
                // 如果选择"就业"，清除项目类型字段
                setFormData((prev) => ({
                    ...prev,
                    [name]: value,
                    project_type: ''
                }));
            } else if (value === '升学') {
                // 如果选择"升学"，清除月薪、年薪和行业字段
                setFormData((prev) => ({
                    ...prev,
                    [name]: value,
                    salary_month: '',
                    salary_year: '',
                    industry_name: ''
                }));
            }
        }

        // 清除对应字段的错误
        if (errors[name]) {
            setErrors((prev) => ({
                ...prev,
                [name]: ''
            }));
        }
    };

    // 验证表单
    const validateForm = (): boolean => {
        const newErrors: Record<string, string> = {};

        // 必填字段验证
        if (!formData.offer_type) {
            newErrors.offer_type = '类型不能为空';
        }

        if (!formData.company_college_name) {
            newErrors.company_college_name = '企业/学校不能为空';
        }

        if (!formData.position_project_name) {
            newErrors.position_project_name = '职位/项目不能为空';
        }

        if (!formData.location) {
            newErrors.location = '地点不能为空';
        }

        // 根据offer类型验证特定字段
        if (formData.offer_type === '升学' && !formData.project_type) {
            newErrors.project_type = '项目类型不能为空';
        }

        if (!formData.accept_status) {
            newErrors.accept_status = '接受情况不能为空';
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    // 处理提交
    const handleSubmit = async () => {
        if (!validateForm()) {
            return;
        }

        setLoading(true);
        setError(null);

        try {
            // 获取当前登录用户ID，这里假设从localStorage中获取
            const uid = localStorage.getItem('uid') || '';

            // 添加uid到表单数据
            const submitData = {
                ...formData,
                uid
            };

            // 调用添加函数
            await onAdd(submitData);

            // 关闭对话框
            onClose();
        } catch (error) {
            console.error('添加工作信息失败:', error);
            setError('添加工作信息失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 处理取消
    const handleCancel = () => {
        onClose();
    };

    // 获取Offer类型选项
    const fetchOfferTypeOptions = async () => {
        try {
            const options = await getOfferTypeOptions();
            setOfferTypeOptions(options);
        } catch (error) {
            console.error('获取Offer类型选项失败:', error);
            setOfferTypeOptions([]);
        }
    };

    // 获取Offer状态选项
    const fetchOfferStatusOptions = async () => {
        try {
            const options = await getOfferStatusOptions();
            setOfferStatusOptions(options);
        } catch (error) {
            console.error('获取Offer状态选项失败:', error);
            setOfferStatusOptions([]);
        }
    };

    // 获取项目类型选项
    const fetchProjectTypeOptions = async () => {
        try {
            const options = await getProjectTypeOptions();
            setProjectTypeOptions(options);
        } catch (error) {
            console.error('获取项目类型选项失败:', error);
            setProjectTypeOptions([]);
        }
    };

    let i = 0;
    const getOptionKey = (option: string) => {
        i++;
        return `${option}${i}`;
    };

    // 处理地区搜索
    const handleLocationSearch = async (value: string) => {
        setLocationSearchInput(value);

        if (value.trim().length < 1) {
            setLocationOptions([]);
            return;
        }

        setLocationSearchLoading(true);
        try {
            const results = await fuzzySearchOfferArea(value);
            setLocationOptions(results);
        } catch (error) {
            console.error('搜索地点失败:', error);
            setLocationOptions([]); // 确保错误时也设置空数组
        } finally {
            setLocationSearchLoading(false);
        }
    };

    // 处理地区选择
    const handleLocationSelect = (_: React.SyntheticEvent, value: string | null) => {
        setFormData((prev) => ({
            ...prev,
            location: value || ''
        }));

        // 清除对应字段的错误
        if (errors.location) {
            setErrors((prev) => ({
                ...prev,
                location: ''
            }));
        }

        // 清空搜索输入值，使下拉框关闭
        setLocationSearchInput('');
    };

    // 处理学校名称搜索
    const handleSchoolSearch = async (value: string) => {
        setSchoolSearchInput(value);

        if (value.trim().length < 1) {
            setSchoolOptions([]);
            return;
        }

        setSchoolSearchLoading(true);
        try {
            const results = await fuzzySearchOfferSchool(value);
            setSchoolOptions(results);
        } catch (error) {
            console.error('搜索企业/学校名称失败:', error);
            setSchoolOptions([]); // 确保错误时也设置空数组
        } finally {
            setSchoolSearchLoading(false);
        }
    };

    // 处理学校名称选择
    const handleSchoolSelect = (_: React.SyntheticEvent, value: string | null) => {
        setFormData((prev) => ({
            ...prev,
            company_college_name: value || ''
        }));

        // 清除对应字段的错误
        if (errors.company_college_name) {
            setErrors((prev) => ({
                ...prev,
                company_college_name: ''
            }));
        }

        // 清空搜索输入值，使下拉框关闭
        setSchoolSearchInput('');
    };

    // 处理职位/项目搜索
    const handleProgramSearch = async (value: string) => {
        setProgramSearchInput(value);

        if (value.trim().length < 1) {
            setProgramOptions([]);
            return;
        }

        setProgramSearchLoading(true);
        try {
            const results = await fuzzySearchOfferProgram(value);
            setProgramOptions(results);
        } catch (error) {
            console.error('搜索职位/项目名称失败:', error);
            setProgramOptions([]); // 确保错误时也设置空数组
        } finally {
            setProgramSearchLoading(false);
        }
    };

    // 处理职位/项目选择
    const handleProgramSelect = (_: React.SyntheticEvent, value: string | null) => {
        setFormData((prev) => ({
            ...prev,
            position_project_name: value || ''
        }));

        // 清除对应字段的错误
        if (errors.position_project_name) {
            setErrors((prev) => ({
                ...prev,
                position_project_name: ''
            }));
        }

        // 清空搜索输入值，使下拉框关闭
        setProgramSearchInput('');
    };

    // 在组件挂载时获取选项
    useEffect(() => {
        fetchOfferTypeOptions();
        fetchOfferStatusOptions();
        fetchProjectTypeOptions().then(() => {
            // 如果没有选项，则手动设置默认值
            setFormData((prev) => ({
                ...prev,
                project_type: '授课型研究生'
            }));
        });
    }, []);

    return (
        <Dialog
            open={open}
            onClose={onClose}
            maxWidth="md"
            fullWidth
            fullScreen={fullScreen}
            slotProps={{
                paper: {
                    sx: {
                        borderRadius: 2,
                        boxShadow: '0 12px 28px rgba(0,0,0,0.15)',
                        overflow: 'hidden'
                    }
                }
            }}>
            <DialogTitle
                sx={{
                    p: 2,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    bgcolor: 'primary.main',
                    color: 'white'
                }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <WorkIcon sx={{ mr: 1 }} />
                    <Typography variant="h6" component="div" sx={{ fontWeight: 500 }}>
                        添加工作信息
                    </Typography>
                </Box>
                <IconButton
                    aria-label="close"
                    onClick={handleCancel}
                    sx={{
                        color: 'white',
                        '&:hover': {
                            backgroundColor: 'rgba(255,255,255,0.1)'
                        }
                    }}>
                    <CloseIcon />
                </IconButton>
            </DialogTitle>

            <DialogContent sx={{ p: 3 }}>
                {error && (
                    <Alert severity="error" sx={{ mb: 2 }}>
                        {error}
                    </Alert>
                )}

                <Box sx={{ mt: 2 }}>
                    <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: 2 }}>
                        {/* 类型 */}
                        <Box>
                            <InputLabel htmlFor="offer_type">类型 *</InputLabel>
                            <FormControl fullWidth error={!!errors.offer_type} size="small">
                                <Select
                                    id="offer_type"
                                    name="offer_type"
                                    value={formData.offer_type}
                                    onChange={handleSelectChange}
                                    sx={{ borderRadius: 1 }}>
                                    {offerTypeOptions.length > 0 ? (
                                        offerTypeOptions.map((type) => (
                                            <MenuItem key={type} value={type}>
                                                {type}
                                            </MenuItem>
                                        ))
                                    ) : (
                                        <>
                                            <MenuItem value="升学">升学</MenuItem>
                                            <MenuItem value="就业">就业</MenuItem>
                                        </>
                                    )}
                                </Select>
                                {errors.offer_type && <FormHelperText>{errors.offer_type}</FormHelperText>}
                            </FormControl>
                        </Box>

                        {/* 企业/学校 */}
                        <Box>
                            <InputLabel htmlFor="company_college_name">企业/学校 *</InputLabel>
                            <Autocomplete
                                id="company_college_name"
                                freeSolo
                                options={schoolOptions}
                                value={formData.company_college_name}
                                inputValue={schoolSearchInput}
                                getOptionKey={getOptionKey}
                                onInputChange={(_, newInputValue) => {
                                    handleSchoolSearch(newInputValue);
                                }}
                                onChange={handleSchoolSelect}
                                loading={schoolSearchLoading}
                                loadingText="搜索中..."
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        name="company_college_name"
                                        variant="outlined"
                                        size="small"
                                        error={!!errors.company_college_name}
                                        helperText={errors.company_college_name}
                                        InputProps={{
                                            ...params.InputProps,
                                            endAdornment: (
                                                <React.Fragment>
                                                    {schoolSearchLoading ? (
                                                        <CircularProgress color="inherit" size={20} />
                                                    ) : null}
                                                    {params.InputProps.endAdornment}
                                                </React.Fragment>
                                            )
                                        }}
                                    />
                                )}
                                sx={{ borderRadius: 1 }}
                            />
                        </Box>

                        {/* 职位/项目 */}
                        <Box>
                            <InputLabel htmlFor="position_project_name">职位/项目 *</InputLabel>
                            <Autocomplete
                                id="position_project_name"
                                freeSolo
                                options={programOptions}
                                value={formData.position_project_name}
                                inputValue={programSearchInput}
                                getOptionKey={getOptionKey}
                                onInputChange={(_, newInputValue) => {
                                    handleProgramSearch(newInputValue);
                                }}
                                onChange={handleProgramSelect}
                                loading={programSearchLoading}
                                loadingText="搜索中..."
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        name="position_project_name"
                                        variant="outlined"
                                        size="small"
                                        error={!!errors.position_project_name}
                                        helperText={errors.position_project_name}
                                        InputProps={{
                                            ...params.InputProps,
                                            endAdornment: (
                                                <React.Fragment>
                                                    {programSearchLoading ? (
                                                        <CircularProgress color="inherit" size={20} />
                                                    ) : null}
                                                    {params.InputProps.endAdornment}
                                                </React.Fragment>
                                            )
                                        }}
                                    />
                                )}
                                sx={{ borderRadius: 1 }}
                            />
                        </Box>

                        {/* 地点 */}
                        <Box>
                            <InputLabel htmlFor="location">地点 *</InputLabel>
                            <Autocomplete
                                id="location"
                                freeSolo
                                options={locationOptions}
                                value={formData.location}
                                inputValue={locationSearchInput}
                                getOptionKey={getOptionKey}
                                onInputChange={(_, newInputValue) => {
                                    handleLocationSearch(newInputValue);
                                }}
                                onChange={handleLocationSelect}
                                loading={locationSearchLoading}
                                loadingText="搜索中..."
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        name="location"
                                        variant="outlined"
                                        size="small"
                                        error={!!errors.location}
                                        helperText={errors.location}
                                        InputProps={{
                                            ...params.InputProps,
                                            endAdornment: (
                                                <React.Fragment>
                                                    {locationSearchLoading ? (
                                                        <CircularProgress color="inherit" size={20} />
                                                    ) : null}
                                                    {params.InputProps.endAdornment}
                                                </React.Fragment>
                                            )
                                        }}
                                    />
                                )}
                                sx={{ borderRadius: 1 }}
                            />
                        </Box>

                        {/* 就业特有字段 */}
                        {formData.offer_type === '就业' && (
                            <>
                                {/* 月薪 */}
                                <Box>
                                    <InputLabel htmlFor="salary_month">月薪</InputLabel>
                                    <TextField
                                        id="salary_month"
                                        name="salary_month"
                                        value={formData.salary_month}
                                        onChange={handleInputChange}
                                        fullWidth
                                        variant="outlined"
                                        size="small"
                                        sx={{ borderRadius: 1 }}
                                    />
                                </Box>

                                {/* 年薪 */}
                                <Box>
                                    <InputLabel htmlFor="salary_year">年薪</InputLabel>
                                    <TextField
                                        id="salary_year"
                                        name="salary_year"
                                        value={formData.salary_year}
                                        onChange={handleInputChange}
                                        fullWidth
                                        variant="outlined"
                                        size="small"
                                        sx={{ borderRadius: 1 }}
                                    />
                                </Box>
                            </>
                        )}

                        {/* 升学特有字段 */}
                        {formData.offer_type === '升学' && (
                            <Box>
                                <InputLabel htmlFor="project_type">项目类型 *</InputLabel>
                                <TextField
                                    id="project_type"
                                    name="project_type"
                                    value={formData.project_type}
                                    onChange={handleInputChange}
                                    fullWidth
                                    variant="outlined"
                                    size="small"
                                    error={!!errors.project_type}
                                    helperText={errors.project_type}
                                    sx={{ borderRadius: 1 }}
                                />
                            </Box>
                        )}

                        {/* 项目类型 */}
                        <Box>
                            <InputLabel htmlFor="project_type">项目类型 *</InputLabel>
                            <FormControl fullWidth error={!!errors.project_type} size="small">
                                <Select
                                    id="project_type"
                                    name="project_type"
                                    value={formData.project_type}
                                    onChange={handleSelectChange}
                                    sx={{ borderRadius: 1 }}>
                                    {projectTypeOptions.length > 0 ? (
                                        projectTypeOptions.map((type) => (
                                            <MenuItem key={type} value={type}>
                                                {type}
                                            </MenuItem>
                                        ))
                                    ) : (
                                        <>
                                            <MenuItem value="授课型研究生">授课型研究生</MenuItem>
                                            <MenuItem value="研究型研究生">研究型研究生</MenuItem>
                                            <MenuItem value="博士">博士</MenuItem>
                                        </>
                                    )}
                                </Select>
                                {errors.project_type && <FormHelperText>{errors.project_type}</FormHelperText>}
                            </FormControl>
                        </Box>

                        {/* 接受情况 */}
                        <Box>
                            <InputLabel htmlFor="accept_status">接受情况 *</InputLabel>
                            <FormControl fullWidth error={!!errors.accept_status} size="small">
                                <Select
                                    id="accept_status"
                                    name="accept_status"
                                    value={formData.accept_status}
                                    onChange={handleSelectChange}
                                    sx={{ borderRadius: 1 }}>
                                    {offerStatusOptions.length > 0 ? (
                                        offerStatusOptions.map((status) => (
                                            <MenuItem key={status} value={status}>
                                                {status}
                                            </MenuItem>
                                        ))
                                    ) : (
                                        <>
                                            <MenuItem value="接受">接受</MenuItem>
                                            <MenuItem value="考虑中">考虑中</MenuItem>
                                            <MenuItem value="放弃">放弃</MenuItem>
                                            <MenuItem value="过期">过期</MenuItem>
                                        </>
                                    )}
                                </Select>
                                {errors.accept_status && <FormHelperText>{errors.accept_status}</FormHelperText>}
                            </FormControl>
                        </Box>
                    </Box>

                    <Box sx={{ mt: 3 }}>
                        <InputLabel htmlFor="remark">备注</InputLabel>
                        <TextField
                            id="remark"
                            name="remark"
                            value={formData.remark}
                            onChange={handleInputChange}
                            fullWidth
                            variant="outlined"
                            size="small"
                            multiline
                            rows={4}
                            sx={{ borderRadius: 1 }}
                        />
                    </Box>
                </Box>
            </DialogContent>

            <Divider />

            <DialogActions sx={{ px: 3, py: 2, justifyContent: 'flex-end' }}>
                <Button
                    onClick={handleCancel}
                    disabled={loading}
                    variant="outlined"
                    sx={{
                        borderRadius: 1.5,
                        px: 3,
                        py: 0.75
                    }}>
                    取消
                </Button>
                <Button
                    onClick={handleSubmit}
                    color="primary"
                    variant="contained"
                    disabled={loading}
                    startIcon={loading ? <CircularProgress size={20} /> : null}
                    sx={{
                        borderRadius: 1.5,
                        px: 3,
                        py: 0.75,
                        boxShadow: '0 4px 10px rgba(0, 0, 0, 0.1)',
                        '&:hover': {
                            boxShadow: '0 6px 12px rgba(0, 0, 0, 0.15)'
                        }
                    }}>
                    {loading ? '提交中...' : '提交'}
                </Button>
            </DialogActions>
        </Dialog>
    );
};

export default AddWorkExperienceDialog;
